package com.itheima.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.common.R;
import com.itheima.constant.TokenConstant;
import com.itheima.dto.LoginDto;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.SMSUtils;
import com.itheima.vo.UserLoginVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("login")
    public R login(@RequestBody LoginDto dto) {
        if (Objects.isNull(dto.getPhone())) {
            return R.error("参数不能为空");
        }
        User user = userService.selectByPhone(dto.getPhone());
        if (Objects.isNull(user)) {
            return R.error("输入的手机号有误,请重新输入");
        }
        System.out.println(dto.getCode());
        Object code = redisTemplate.opsForValue().get("code");
        if (!dto.getCode().equals(code)) {
            return R.error("验证码有误,请重新输入");
        }
        String s = System.currentTimeMillis() + user.getId();
        String token = DigestUtils.md5DigestAsHex(s.getBytes());

        redisTemplate.opsForValue().set(TokenConstant.USER_TOKEN_PREFIX + token, JSON.toJSONString(user), 259200, TimeUnit.SECONDS);
        UserLoginVo userLoginVo = new UserLoginVo();
        BeanUtils.copyProperties(user, userLoginVo);
        userLoginVo.setToken(token);

        return R.success(userLoginVo);
    }

    @PostMapping("sendMsg")
    public R sendMsg(@RequestBody User user) {
        if (Objects.isNull(user.getPhone())) {
            return R.error("参数不能为空");
        }
        String phone = user.getPhone();
        User user1 = userService.selectByPhone(phone);
        if (Objects.isNull(user1)) {
            return R.error("该手机号未注册");
        }

        Random random = new Random();
        int result = random.nextInt(9000 - 1000 + 1) + 1000;
        String code = String.valueOf(result);
        System.out.println("您的短信验证码为：" + code);
        redisTemplate.opsForValue().set("code", code, 300, TimeUnit.SECONDS);
        return R.success("发送成功");
    }

        @PostMapping("loginout")
        public R<String> loginOut(HttpServletRequest request){

            String token = request.getHeader("AuthorizationUser");
            redisTemplate.delete(token);
            return R.success("退出成功");

        }
    }



